//
//  YZMStockEntrustView.m
//  YZMicroStock
//
//  Created by wangminhong on 16/4/12.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMStockEntrustView.h"
#import "YZMStockInfoView.h"
#import "YZMyStocksService.h"
#import "YZMStockQuotePanelView.h"
#import "YZMStockRealModel.h"
#import "YZMStockRealDictModel.h"
#import "YZMyStocksService.h"
#import "YZMConfigureService.h"
#import "NSNumber+Utils.h"
#import "YZClient.h"
#import "YZMAlertView.h"
#import "NSError+YZM.h"
#import "YZMStockViewController.h"
#import <BlocksKit/UIControl+BlocksKit.h>
#import "YZMOneyuanViewController.h"
#import "YZMDelayCharge.h"
#import "YZClient+WaitPay.h"
#import "YZClient+FreeExperience.h"
#import "YZMFreeExperienceViewController.h"
#import "WclAlterView.h"
#import "NSNumber+Utils.h"
#import "YZMHomeRankListModel.h"
#import "YZMHomeTrendModel.h"
#import "YZMTrendCell.h"
#import "YZMStockSearchService.h"
#import "YZMSimulateViewController.h"

#define TrendCellHeight 60

static NSString *const home_page_master_cell_identifier = @"YZMTrendCell";

@interface YZMStockEntrustView()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong, readwrite) UIScrollView *scrollView;
@property (nonatomic, strong) UITableView*  masterTV;
@property (nonatomic, strong) NSMutableArray *rankStrategyArray;

@property (nonatomic, strong) YZMStockInfoView *infoView;
@property (nonatomic, strong) YZMStockQuotePanelView *quoteView;
@property (nonatomic, strong) YZMStockRealModel *stockReal;
@property (nonatomic, strong) UIButton *submitButton;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) NSTimer *buttonTimer;
@property (nonatomic, copy) NSString  *stockCode;
@property (nonatomic, copy) NSString  *stockName;
@property (nonatomic, assign) BOOL unFirstFetchFlag;
@property (nonatomic, assign) BOOL unShowErrorFlag;//断网后只显示一次错误
@property (nonatomic, assign) YZM_TRADE_TYPE tradeType;
@property (nonatomic, strong) YZMConfigureService *service;
@property (nonatomic, strong) NSMutableDictionary *params;
@property (nonatomic, strong) YZMRedPacketInfor *redpackModel;

@end

@implementation YZMStockEntrustView

- (UITableView *)masterTV {
    if (!_masterTV) {
        _masterTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height) style:UITableViewStylePlain];
        _masterTV.delegate = self;
        _masterTV.dataSource = self;
        _masterTV.backgroundView = nil;
        _masterTV.backgroundColor = [UIColor clearColor];
        _masterTV.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_masterTV registerClass:[YZMTrendCell class] forCellReuseIdentifier:home_page_master_cell_identifier];
    }
    return _masterTV;
}

- (NSMutableArray *)rankStrategyArray {
    if (!_rankStrategyArray) {
        _rankStrategyArray = [NSMutableArray array];
    }
    return _rankStrategyArray;
}

- (instancetype)initWithFrame:(CGRect)frame andTradeType:(YZM_TRADE_TYPE)tradeType {
    
    self = [super initWithFrame:frame];
    if (self) {
        _tradeType = tradeType;
        _service = [YZMConfigureService sharedServiceWithTradeType:_tradeType];
        self.backgroundColor = [YZMAppStyle appBackgroundColor];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getUseRedpacket:) name:@"TDUseRedPack" object:nil];
        [self createObjects];
    }
    return self;
}

-(void)getUseRedpacket:(NSNotification *)noti{
    
    self.params[@"useTip"] = noti.userInfo[@"isuseRedpack"];
}




- (NSMutableDictionary *)params {
    
    if (!_params) {
    
        _params = [NSMutableDictionary dictionary];
        _params[@"useTip"] = @(NO);
    }
    return _params;
}

#pragma mark -- event
- (void)stockBuyButtonPressed:(UIButton  *)sender{
    
    if (kNetworkNotReachability) {
        [NSError yz_showMessageForNoWifi];
        return;
    }

    //判断是否已经获取行情数据
    if (!self.stockReal) {
        [MBProgressHUD showMessage:@"暂未获取股票行情信息"];
        return;
    }

    //判断交易时间
    if (![self.service isInTradeTimePeriods]) {
        self.submitButton.enabled = NO;
        [[YZMAlertView alertViewForRecommandWithContent:@"非点买时段"] showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }
    
    //风险股判断
    if ( [@(fabs(self.stockReal.price/self.stockReal.lastClosePrice - 1.0)) isEqualGreaterThanDouble:0.08] ) {
        [[YZMAlertView alertViewForRecommandWithContent:@"今日点买风险较高，暂无投资人接收交易合作"] showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }

    //停盘股判断
    if ( [@(self.stockReal.price) isEqualWithDouble:0.0] ) {
        [[YZMAlertView alertViewForRecommandWithContent:@"停牌股暂时无法进行买卖"] showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }
    
    //限制股判断
    if ([self.service isInLimitStockListWithStockCode:self.stockReal.code]) {
        [[YZMAlertView alertViewForRecommandWithContent:@"该股今日为禁买股，请选择其他股票交易"] showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }
    
    //是否登录
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D) {
        
        if (!YZMUserServiceInstance.currentUser) {
            [YZMUserService showLoginCtrlWithSourcePageName:@"stockTD"];
            return;
        }
    }
    
 
    //是否登录
    if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK || self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
        
        if (!YZMUserServiceInstance.currentUser) {
            [YZMUserService showLoginCtrlWithPageName:@"stockBuy" andPageParams:@{@"stockReal":self.stockReal,@"tradeType":@(self.tradeType)}];
            return;
        }
    }
    
    switch (self.tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK:
            [self showAlterViewWithWaitPay];
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
            [self showAlterViewWithYlb];
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:
            if (self.schemeModel) {
                self.params[@"ID"] = @(self.schemeModel.Id);
                //发起点买策略
                [self createStrategy];
                return;
            } else{

                [YZMHCMInstance pushViewControllerWithName:@"stockTDBuy" andParams:nil];
            }
            break;

        case YZM_TRADE_TYPE_FOR_A_STOCK_ONE:
            [self createStrageyForOney];
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:
            [YZMHCMInstance pushViewControllerWithName:@"stockBuy" andParams:@{@"stockReal":self.stockReal,@"tradeType":@(self.tradeType)}];
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:{
            //是否为新用户
            if (self.service.defaultConfigure.userType==2) {
                
                [[YZMAlertView alertViewForRecommandWithContent:@"该活动仅限新注册用户参加"] showInView:YZMHCMInstance.currentNavationCtroller.view];
                
                return;
            }
            
            //是否为参加过一元实盘体验
            if (self.service.defaultConfigure.userType==3) {
                
                [[YZMAlertView alertViewForRecommandWithContent:@"您已参加过此活动"] showInView:YZMHCMInstance.currentNavationCtroller.view];
                return;
            }
            
            //是否点买过
            if (self.service.defaultConfigure.userType==4) {
                
                [[YZMAlertView alertViewForRecommandWithContent:@"您已经参与过A股实盘交易，无法体验"] showInView:YZMHCMInstance.currentNavationCtroller.view];
                
                return;
            }
            [self showAlterViewWithFreeExperience];
        }
            break;
            
        default:
            break;
    }
}

- (void)showAlterViewWithFreeExperience{
    NSLog(@"stockReal:%@,param:%@",self.stockReal,self.params);
    
    NSMutableArray *array = [NSMutableArray array];
    NSDictionary *dicName = @{@"股票名称：":self.stockReal.name};
    NSDictionary *dicCode = @{@"股票代码：":self.params[@"stockCode"]};
    NSDictionary *dicPrice = @{@"委托价格：":@"市价"};
    NSDictionary *dicCount = @{@"买入数量":[NSString stringWithFormat:@"%@股",self.params[@"amount"]]};
    NSDictionary *dicDays = @{@"持仓天数：":@"2天"};
    [array addObject:dicName];
    [array addObject:dicCode];
    [array addObject:dicCount];
    [array addObject:dicPrice];
    [array addObject:dicDays];
    WS(ws);
    WclAlterView *alterView = [WclAlterView altertViewWithTitle:@"点买确认" array:array confirmHandle:^{
        [ws createStrageyForFreeExperience];
    }];
    [alterView show];

//    WS(ws);
//    YZMAlertView *altertView = [YZMAlertView ];
//    altertView.cancelButton.hidden = NO;
//    [altertView.sureButton setTitle:@"确认" forState:UIControlStateNormal];
//    UIWindow *wd = [UIApplication sharedApplication].keyWindow;
//    altertView.confirmHandle = ^BOOL{
//        [ws  createStrageyForFreeExperience];
//        return YES;
//    };
//    [altertView showInView:wd];
}


- (void)showAlterViewWithWaitPay{
    WS(weakSelf);
    [YZMDelayCharge showDelayChargeViewWithConfirmHandle:^BOOL{
        [YZMHCMInstance pushViewControllerWithName:@"stockBuy" andParams:@{@"stockReal":weakSelf.stockReal,@"tradeType":@(weakSelf.tradeType)}];
        return YES;
    } cancleHandle:nil noWaitPayHandle:^{
        [YZMHCMInstance pushViewControllerWithName:@"stockBuy" andParams:@{@"stockReal":weakSelf.stockReal,@"tradeType":@(weakSelf.tradeType)}];
    }];
}

- (void)showAlterViewWithYlb{
    [YZMHCMInstance pushViewControllerWithName:@"stockBuy" andParams:@{@"stockReal":self.stockReal,@"tradeType":@(self.tradeType)}];
}

- (void)notifictaonWithParams:(NSNotification *)noti {
    
    NSDictionary *dic = noti.userInfo;
    self.params[@"amount"] = dic[@"amount"];
    self.params[@"chargePrice"] = dic[@"chargePrice"];
    self.params[@"money"] = dic[@"money"];
    self.params[@"stockCode"] = self.stockCode;
}

-(void)notificationForAmount:(NSNotification *)noti{
    self.params[@"stockCode"] = self.stockCode;
    self.params[@"amount"]=noti.userInfo[@"oneyamount"];
}

#pragma mark -- Network
- (void)createStrategy {

    [YZMCMInstance pushViewControllerWithName:@"BuyForD" andParams:@{@"stockCode":self.stockCode,@"stockName":self.stockName,@"schemeModel":self.schemeModel}];
//    if (kNetworkNotReachability) {
//        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
//        return;
//    }
//    
//    double money;
//    if ([self.params[@"useTip"] boolValue]) {
//    
//        if ( [@(self.redpackModel.tipBalance) isEqualGreaterThanDouble:[self.params[@"chargePrice"] doubleValue]]) {
//            money = [self.params[@"money"] doubleValue] - self.schemeModel.availableMoney;
//        }else{
//            
//            money = [self.params[@"chargePrice"] doubleValue] + [self.params[@"money"] doubleValue] - ( self.redpackModel.tipBalance + self.schemeModel.availableMoney);
//        }
//    }else{
//        
//        money = [self.params[@"chargePrice"] doubleValue] + [self.params[@"money"] doubleValue] - self.schemeModel.availableMoney;
//    }
//    
//    //余额判断
//    if ( [@(money) isGreaterThanDouble:0.0] ) {
//        //余额不足
//        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.frame];
//        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
//        alertView.contentLabel.text = [NSString stringWithFormat:@"策略组余额不足,无法买入,请到个人中心-我的策略组-追加点买金"];
//        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
//        return;
//    }
//    
//    //交易数量判断
//    if ([self.params[@"amount"] integerValue] > self.service.defaultConfigure.maxStockCount) {
//        
//        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.frame];
//        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
//        alertView.contentLabel.text = @"单只股票交易数量已达到上限";
//        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
//        return;
//    }
//    
//    //方案是否当天到期
//    if (self.schemeModel.availableDays == 0) {
//        
//        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.frame];
//        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
//        alertView.contentLabel.text = [NSString stringWithFormat:@"您的T+D点买策略组即将到期，不允许买入！"];
//        
//        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
//        return;
//    }
//    
//    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"提交中"];
//    [YZClient td_createStrategyWithParams:self.params success:^(NSURLSessionDataTask *task, id responseObject){
//
//        YZGeneralResultModel *topModel=responseObject;
//        [hud hide:YES];
//        if (topModel.success) {
//            
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshScheme" object:nil];
//            [MBProgressHUD showMessage:@"点买成功"];
//            [YZMUserServiceInstance fetchUserAssetsInfo];
//            UIViewController *viewController = [YZMHCMInstance instanceWithControllerName:@"stockTD"];
//            if(viewController){
//                
//                YZMStockViewController *tradeVC = (YZMStockViewController *)viewController;
//                [tradeVC showSellListPage];
//            }
//        }else{
//            NSString *token = [topModel.data objectForKey:@"token"];
//            if (token.length >0) {
//                
//                self.service.defaultConfigure.token = token;
//            }
//            [topModel showMessage];
//        }
//    } failure:^(NSError *error) {
//        [hud hide:YES];
//        [error yz_showMessage];
//    }];
}



#pragma mark oneyuan createStragey
-(void)createStrageyForOney{
    
    if (kNetworkNotReachability) {
        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
        return;
    }
    
    //实名认证判断
    if (!YZMUserServiceInstance.user.detail.isNamed) {
        YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"您还未实名认证，请先认证"];
        alertView.cancelButton.hidden = NO;
        [alertView.sureButton setTitle:@"立即验证" forState:UIControlStateNormal];
        alertView.confirmHandle = ^{
            [YZMHCMInstance pushViewControllerWithName:@"identifyVerify" andParams:nil];
            return YES;
        };
        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }
    
//    //交易数量判断
//    if ([self.params[@"amount"] integerValue] > self.service.defaultConfigure.maxStockCount) {
//        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.frame];
//        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
//        alertView.contentLabel.text = @"单只股票交易数量已达到上限";
//        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
//        return;
//    }

    //是否为新用户
//    if (self.service.defaultConfigure.userType==2) {
//        
//        [[YZMAlertView alertViewForRecommandWithContent:@"该活动只限新用户（2016.12.15日起新注册用户？）"] showInView:YZMHCMInstance.currentNavationCtroller.view];
//
//        return;
//    }
    
    //是否为参加过一元实盘体验
    if (self.service.defaultConfigure.userType==3) {
        
        [[YZMAlertView alertViewForRecommandWithContent:@"您已参加过此活动"] showInView:YZMHCMInstance.currentNavationCtroller.view];

        return;
    }
    
    //是否点买过
    if (self.service.defaultConfigure.userType==4) {
        
        [[YZMAlertView alertViewForRecommandWithContent:@"您已经参与过A股实盘交易，无法体验"] showInView:YZMHCMInstance.currentNavationCtroller.view];

        return;
    }
    
    if ( ![@(self.service.defaultConfigure.balance) isEqualGreaterThanDouble:1.0] ) {
        //余额不足
        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.frame];
        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        alertView.contentLabel.textColor = [YZMAppStyle colorForBlackText];
        alertView.confirmHandle = ^{
            [YZMHCMInstance pushViewControllerWithName:@"recharge" andParams:@{YZBACKFLAG:@(YES)}];
            return YES;
        };
        alertView.contentLabel.text = @"当前余额不足\n请充值后再发起策略";
        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }
    
    self.params[@"token"]=self.service.defaultConfigure.token;
    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"提交中"];
    [YZClient oneY_createStrategyWithParams:self.params success:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *model=responseObject;
        [hud hide:YES];
        if (model.success) {
            [MBProgressHUD showMessage:@"点买成功"];
            [YZMUserServiceInstance fetchUserAssetsInfo];
            UIViewController *viewController = [YZMHCMInstance instanceWithControllerName:@"oneYuan"];
            if (viewController) {
                YZMOneyuanViewController *oneVC=(YZMOneyuanViewController *)viewController;
                [oneVC showSellListPage];
            }
        }else{
            NSString *token=[model.data objectForKey:@"token"];
            if (token.length>0) {
                self.service.defaultConfigure.token=token;
            }
            if (self.service.defaultConfigure.userType==2) {
                [[YZMAlertView alertViewForRecommandWithContent:model.resultMessage] showInView:YZMHCMInstance.currentNavationCtroller.view];
            }else{
                [model showMessage];
            }
        }
    } failure:^(NSError *error) {
        [hud hide:YES];
        [error yz_showMessage];
    }];
}

#pragma mark freeExperience createStragey
- (void)createStrageyForFreeExperience{
        if (kNetworkNotReachability) {
            [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
            return;
        }
        
        //实名认证判断
        if (!YZMUserServiceInstance.user.detail.isNamed) {
            YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"您还未实名认证，请先认证"];
            alertView.cancelButton.hidden = NO;
            [alertView.sureButton setTitle:@"立即验证" forState:UIControlStateNormal];
            alertView.confirmHandle = ^{
                [YZMHCMInstance pushViewControllerWithName:@"identifyVerify" andParams:nil];
                return YES;
            };
            [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
            return;
        }
        
        //    //交易数量判断
        //    if ([self.params[@"amount"] integerValue] > self.service.defaultConfigure.maxStockCount) {
        //        YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.frame];
        //        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        //        alertView.contentLabel.text = @"单只股票交易数量已达到上限";
        //        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
        //        return;
        //    }
        
        //是否为新用户
            if (self.service.defaultConfigure.userType==2) {
        
                [[YZMAlertView alertViewForRecommandWithContent:@"该活动仅限新注册用户参加"] showInView:YZMHCMInstance.currentNavationCtroller.view];
        
                return;
            }
    
        //是否为参加过一元实盘体验
        if (self.service.defaultConfigure.userType==3) {
            
            [[YZMAlertView alertViewForRecommandWithContent:@"您已参加过此活动"] showInView:YZMHCMInstance.currentNavationCtroller.view];
            return;
        }
        
        //是否点买过
        if (self.service.defaultConfigure.userType==4) {
            
            [[YZMAlertView alertViewForRecommandWithContent:@"您已经参与过免费体验，无法进行点买"] showInView:YZMHCMInstance.currentNavationCtroller.view];
            
            return;
        }
        
//        if ( ![@(self.service.defaultConfigure.balance) isEqualGreaterThanDouble:1.0] ) {
//            //余额不足
//            YZMAlertView *alertView = [[YZMAlertView alloc] initWithFrame:self.frame];
//            alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
//            alertView.contentLabel.textColor = [YZMAppStyle colorForBlackText];
//            alertView.confirmHandle = ^{
//                [YZMHCMInstance pushViewControllerWithName:@"recharge" andParams:@{YZBACKFLAG:@(YES)}];
//                return YES;
//            };
//            alertView.contentLabel.text = @"当前余额不足\n请充值后再发起策略";
//            [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
//            return;
//        }
    
        self.params[@"token"]=self.service.defaultConfigure.token;
        MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"提交中"];
        [YZClient freeEx_createStrategyWithParams:self.params success:^(NSURLSessionDataTask *task, id responseObject) {
            YZGeneralResultModel *model=responseObject;
            [hud hide:YES];
            if (model.success) {
                [MBProgressHUD showMessage:@"点买成功"];
                [YZMUserServiceInstance fetchUserAssetsInfo];
                UIViewController *viewController = [YZMHCMInstance instanceWithControllerName:@"freeExperience"];
                if (viewController) {
                    YZMFreeExperienceViewController *freeExVC=(YZMFreeExperienceViewController *)viewController;
                    [freeExVC showSellListPage];
                }
            }else{
                NSString *token=[model.data objectForKey:@"token"];
                if (token.length>0) {
                    self.service.defaultConfigure.token=token;
                }
                if (self.service.defaultConfigure.userType==2) {
                    [[YZMAlertView alertViewForRecommandWithContent:model.resultMessage] showInView:YZMHCMInstance.currentNavationCtroller.view];
                }else{
                    [model showMessage];
                }
            }
        } failure:^(NSError *error) {
            [hud hide:YES];
            [error yz_showMessage];
        }];
}

#pragma mark -- configure data fetch
- (void)checkIfNeedRequestConfigureData{
    
    if(kNetworkNotReachability){
        [self startButtonTimer];
        return;
    }
    
    switch (self.tradeType) {
        case YZM_TRADE_TYPE_FOR_A_STOCK:{
            [self.service checkIfNeedRequestConfigureWithSuccess:^(){
                
                [self refreshData];
                //刷新按钮可用性，非交易时间不可点
                [self startButtonTimer];
            }];
        }
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_D:{
            [self.service fetchConfigureDataSuccess:^{
                
                [self refreshData];
                //刷新按钮可用性，非交易时间不可点
                [self startButtonTimer];
            } failure:nil];
        }
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:{
            [self.service checkIfNeedRequestConfigureWithSuccess:^(){
                
                [self refreshData];
                //刷新按钮可用性，非交易时间不可点
                [self startButtonTimer];
            }];
        }

        case YZM_TRADE_TYPE_FOR_A_STOCK_ONE:{
            [self.service fetchConfigureDataSuccess:^{
                [self refreshData];
                [self startButtonTimer];
            } failure:nil];
        }
            break;
            
        case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:{
            [self.service fetchConfigureDataSuccess:^{
            //活动结束前两日不能交易
            [self getbasicData];
            if (self.service.defaultConfigure.gameTimeStatus==2) {
                [self.submitButton setTitle:@"立即点买" forState:UIControlStateDisabled];
                self.submitButton.enabled = NO;
                return ;
            }
            [self refreshData];
            [self startButtonTimer];
            } failure:nil];
        }
            break;
        case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:{
            [self.service fetchConfigureDataSuccess:^{
                [self refreshData];
                [self startButtonTimer];
            } failure:nil];
        }
            break;
            
        default:
            break;
    }
}


-(void)fetchTrendListData{
    
//    if ([self checkNetwork]) {
//        return;
//    }
    
    [YZClient fetchHomeTrendListWithSuccess:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"endRefreshing" object:nil];
            YZMHomeTrendModel *model = topModel.data;
            [self.rankStrategyArray removeAllObjects];
            [self.rankStrategyArray addObjectsFromArray:(NSArray *)model];
            [self.masterTV reloadData];
            [self.masterTV mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(self.quoteView.mas_bottom).offset(-100);
                make.left.right.equalTo(self.scrollView);
                make.height.mas_equalTo(_rankStrategyArray.count * TrendCellHeight);
                make.bottom.equalTo(self.scrollView).offset(-10);
            }];
            
            WS(weakSelf)
            self.quoteView.block = ^(NSUInteger index) {
               
                    if (index == 0) {
                        [weakSelf.masterTV mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(weakSelf.quoteView.mas_bottom).offset(-110);
                        }];
                    } else if(index == 4) {
                        [weakSelf.masterTV mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(weakSelf.quoteView.mas_bottom).offset(-110);
                        }];
                    } else {
                        [weakSelf.masterTV mas_updateConstraints:^(MASConstraintMaker *make) {
                            make.top.equalTo(weakSelf.quoteView.mas_bottom).offset(-200);
                        }];
                    }
               
            };
            
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
        
    }];
}

- (BOOL)checkNetwork {
    
    if (kNetworkNotReachability) {
        self.hidden = YES;
        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
        
        return YES;
    }
    self.hidden = NO;
    return NO;
}

#pragma mark -- timer action

- (void)updateWithStockCode:(NSString *)stockCode andStockName:(NSString *)stockeName{
    
    self.stockCode = stockCode;
    self.stockName = stockeName;
    self.stockReal = nil;
    [self.infoView updateWithStockCode:self.stockCode andStockName:self.stockName];
    [self.quoteView updateWithStockCode:self.stockCode];
    [self buttonUpdateTimer:nil];
}

- (void)requestToLoadReal{
    
    __weak typeof(&*self) safeSelf = self;
    [YZClient qt_getRealtimeInfoWithStockCodes:@[self.stockCode] success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            NSDictionary *dict = topModel.data;
            if (!safeSelf.stockReal) {
                safeSelf.stockReal = dict[self.stockCode];
                [safeSelf buttonUpdateTimer:nil];
            }
            safeSelf.stockReal = dict[self.stockCode];
            safeSelf.infoView.realStock = dict[self.stockCode];
            if ( [@(safeSelf.stockReal.price) isEqualGreaterThanDouble:0.0] ) {
            
                [safeSelf.quoteView updateRealInfo:dict[self.stockCode]];
                [safeSelf.quoteView refreshData];
            }
        }else{
            [safeSelf stopTimer];
            [topModel showMessage];
        }
        
        self.unShowErrorFlag = NO;
    } failure:^(NSError *error) {
        if (!self.unShowErrorFlag) {
            [error yz_showMessage];
        }
    }];
}

#pragma mark netWorking
-(void)fetchActivityRedPacketInfor{
    
    WS(ws)
    [YZClient Activity_RedpacketInforsuccess:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            ws.redpackModel = topModel.data;
            ws.quoteView.inforModel = ws.redpackModel;
            if ([@(ws.redpackModel.tipBalance) isGreaterThanDouble:0]) {
                
                ws.params[@"useTip"] = @(YES);
            }else{
                
                [[NSNotificationCenter defaultCenter]postNotificationName:@"deleteRedPacketView" object:nil];
            }
        }else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)refreshData
{
    [self requestToLoadReal];
    
    self.quoteView.defaultMode=self.service.defaultConfigure;
    
}

- (void)dataUpdateTimer: (NSTimer *)timer
{
    if (kNetworkNotReachability) {
        if (!self.unShowErrorFlag) {
            [MBProgressHUD showMessage:@"网络无法连接，无法获取行情信息"];
            self.unShowErrorFlag = YES;
        }
        return;
    }
    
    if (!self.unFirstFetchFlag || [self.service isInTradeTimePeriods]){
        [self refreshData];
        self.unFirstFetchFlag = YES;
    }
}

- (void)buttonUpdateTimer:(NSTimer *)timer{
    if ([self.service isInLimitStockListWithStockCode:self.stockCode] || (self.stockReal && [@(self.stockReal.price) isEqualWithDouble:0.0]) ) {
        
        [self.submitButton setTitle:@"立即点买" forState:UIControlStateDisabled];
        if (self.tradeType==YZM_TRADE_TYPE_FOR_A_STOCK_SIM) {
            [self getbasicData];
        }
//        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_D) {
//            
//            [self.submitButton setTitle:@"立即点买" forState:UIControlStateDisabled];
//        } else {
//            [self.submitButton setTitle:@"点买" forState:UIControlStateDisabled];
//            if (self.tradeType==YZM_TRADE_TYPE_FOR_A_STOCK_SIM) {
//                [self getbasicData];
//            }
//        }
        self.submitButton.enabled = NO;
        return;
    }
    
    [self.submitButton setTitle:@"非点买时段" forState:UIControlStateDisabled];
    self.submitButton.enabled = [self.service isInTradeTimePeriods];
}

#pragma mark -- timer

- (void)startTimer
{
    if (self.timer == nil) {
        self.timer = [NSTimer timerWithTimeInterval: 1.0 target:self selector: @selector(dataUpdateTimer:) userInfo: nil repeats: YES];
        [[NSRunLoop mainRunLoop] addTimer: self.timer forMode: NSRunLoopCommonModes];
        [self.timer fire];
    }
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notifictaonWithParams:) name:@"strategyParams" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(notificationForAmount:) name:@"ONEYUANAMOUNT" object:nil];
}

- (void)stopTimer
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)startButtonTimer{
    
    if (self.buttonTimer == nil) {
        self.buttonTimer = [NSTimer timerWithTimeInterval: 60.0 target:self selector: @selector(buttonUpdateTimer:) userInfo: nil repeats: YES];
        [[NSRunLoop mainRunLoop] addTimer: self.buttonTimer forMode: NSRunLoopCommonModes];
        [self.buttonTimer fire];
    }
}

- (void)stopButtonTimer{
    
    if (self.buttonTimer) {
        [self.buttonTimer invalidate];
        self.buttonTimer = nil;
    }
}

-(void)getbasicData{
    [YZClient simU_getBasicDataSuccess:^(NSURLResponse *response, id responseObject) {
        YZGeneralResultModel *model=responseObject;
        if (model.success) {
            NSDictionary *dic=model.data;
            NSNumber *status=[dic objectForKey:@"gameStatus"];
            
            if ([status intValue]==3) {
                _submitButton.enabled=NO;
                [_submitButton setTitle:@"比赛已结束" forState:UIControlStateDisabled];
            }else if([status intValue]==1){
                _submitButton.enabled=NO;
                [_submitButton setTitle:@"比赛未开始" forState:UIControlStateDisabled];
            }
        }else{
            [model showMessage];
        }
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}

#pragma mark -- ui

- (void)setSchemeModel:(YZMMyStackModel *)schemeModel {
    
    _schemeModel = schemeModel;
    self.quoteView.schemeModel = schemeModel;
}

- (void)createObjects
{
    UIView *bottomView = [UIView new];
    bottomView.backgroundColor = [YZMAppStyle tabbarBackgroundColor];
    [self addSubview:bottomView];
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self);
        if (iPhoneX) {
            make.bottom.equalTo(self).with.offset(-34);
        }else{
            make.bottom.equalTo(self);
        }
        make.bottom.mas_equalTo(50);
        make.left.equalTo(self);
    }];
    
    UIView *lineView = [YZMAppStyle splitLine];
    [bottomView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(bottomView);
    }];
    
    self.submitButton = [YZMAppStyle submitButton];
    self.submitButton.enabled = YES;
    
    [self.submitButton setTitle:@"立即点买" forState:UIControlStateNormal];
    
    [self.submitButton setTitle:@"非点买时段" forState:UIControlStateDisabled];
    [self.submitButton addTarget:self action:@selector(stockBuyButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:self.submitButton];
    [self.submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(bottomView).insets(UIEdgeInsetsMake(15, 15, 15, 15));
    }];

    
    self.scrollView = [[UIScrollView alloc] init];
    [self addSubview: self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.bottom.equalTo(bottomView.mas_top);
        make.width.equalTo(self);
    }];

    __weak __typeof(&*self) weakSelf = self;
    self.infoView = [YZMStockInfoView new];
    self.infoView.changeAction = ^(){
        
    [YZMHCMInstance pushViewControllerWithName:@"customAdd" andParams:@{@"tradeType":@(weakSelf.tradeType)}];
    };
    
    self.infoView.operationAction = ^(BOOL addFlag){
        if(addFlag){
            
           return [[YZMyStocksService sharedService] addStockWithCode:weakSelf.stockCode andName:weakSelf.stockName];
        }
        else{
            
           return [[YZMyStocksService sharedService] removeStockWithCode:weakSelf.stockCode];
        }
    };
    [self.scrollView addSubview: self.infoView];
    [self.infoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.scrollView);
        make.width.equalTo(self.scrollView);
    }];


    self.quoteView  = [[YZMStockQuotePanelView alloc] initWithFrame:CGRectZero andTradeType:self.tradeType];
    self.quoteView.backgroundColor = [UIColor clearColor];
    self.quoteView.defaultMode=self.service.defaultConfigure;
    [self.scrollView addSubview: self.quoteView];
    [self.quoteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.infoView.mas_bottom);
        make.left.right.equalTo(self.scrollView);
        if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_FREE  || self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_ONE ) {
        make.bottom.equalTo(self.scrollView).offset(-30);
        }
    }];
    
    if (!(self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_FREE || self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_ONE)) {
        [self.scrollView addSubview:self.masterTV];
        [self fetchTrendListData];
        
    }
    [self fetchActivityRedPacketInfor];
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return TrendCellHeight;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.rankStrategyArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
        
    YZMTrendCell *cell = [tableView dequeueReusableCellWithIdentifier:home_page_master_cell_identifier forIndexPath:indexPath];
    WS(ws)
    cell.handle = ^{
        [ws tradeWith:indexPath];
    };
    cell.numberForColor = indexPath.row;
    
    YZMHomeTrendModel *trendModel = _rankStrategyArray[indexPath.row];
    cell.trendModel = trendModel;
    
    YZMIndexCount indexCount;
    indexCount.index = indexPath.row;
    indexCount.count = _rankStrategyArray.count;
    cell.indexCount = indexCount;
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self tradeWith:indexPath];
}

- (void)tradeWith:(NSIndexPath *)indexPath{
    if (indexPath.row<_rankStrategyArray.count) {
        YZMHomeTrendModel *trendModel = _rankStrategyArray[indexPath.row];
        if (trendModel.stockCode.length == 0) {
            return;
        }
        NSDictionary *param = nil;
        if (trendModel.stockName.length == 0) {
            param= @{@"stockcode":trendModel.stockCode};
        }else{
            param = @{@"stockcode":trendModel.stockCode,@"stockname":trendModel.stockName};
        }
        
        YZMStockViewController *tradeVC = nil;
        YZMOneyuanViewController *oneVC=nil;
        YZMFreeExperienceViewController *freeVc = nil;
        YZMSimulateViewController* simVC = nil;
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"UpdateCurrentIndex" object:nil userInfo:@{@"currentIndex":@(0)}];
        
        switch (self.tradeType) {
            case YZM_TRADE_TYPE_FOR_A_STOCK:
            case YZM_TRADE_TYPE_FOR_A_STOCK_YLB:
            {
                if (self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_YLB) {
                    tradeVC = [YZMHCMInstance instanceWithControllerName:@"stockYLB"];
                }else{
                    tradeVC = [YZMHCMInstance instanceWithControllerName:@"stock"];
                }
                [tradeVC updateWithParamsManual:param];
            }
                break;
                
            case YZM_TRADE_TYPE_FOR_A_STOCK_D: {
                tradeVC = [YZMHCMInstance instanceWithControllerName:@"stockTD"];
                [tradeVC updateWithParamsManual:param];
            }
                break;
                
            case YZM_TRADE_TYPE_FOR_A_STOCK_ONE:{
                oneVC = [YZMHCMInstance instanceWithControllerName:@"oneYuan"];
                [oneVC updateWithParamsManual:param];
            }
                break;
            case YZM_TRADE_TYPE_FOR_A_STOCK_FREE:{
                freeVc = [YZMHCMInstance instanceWithControllerName:@"freeExperience"];
                [freeVc updateWithParamsManual:param];
            }
                break;
                
            case YZM_TRADE_TYPE_FOR_A_STOCK_SIM:
                simVC = [YZMHCMInstance instanceWithControllerName:@"Simulate"];
                [simVC updateWithParamsManual:param];
                break;
                
            default:
                break;
        }
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.scrollView.contentOffset = CGPointMake(0, 0);
    }];
    
}

-(void)updateCurrentIndex:(NSInteger)currentIndex{
    
    [self.quoteView updateCurrentIndex:currentIndex];
}

-(void)updateRedpacket{
    if (!(self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_FREE || self.tradeType == YZM_TRADE_TYPE_FOR_A_STOCK_ONE)) {
        [self fetchTrendListData];
    }
    [self fetchActivityRedPacketInfor];
}

@end
